package com.pwp.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.agent.crm.base.BaseActivity;
import com.agent.crm.sechdule.receiver.RepeatingAlarm;
import com.agent.crm.util.MoveBg;
import com.agent.crm.view.MainActivity;
import com.agent.crm.view.NoteBookActivity;
import com.agent.crm.view.R;
import com.agent.crm.view.SearchActivity;
import com.pwp.constant.CalendarConstant;
import com.pwp.dao.ScheduleDAO;
import com.pwp.vo.ScheduleVO;

public class CalendarWeekActivity extends BaseActivity {
	
	private ScheduleDAO dao = null;
//	private ScheduleVO scheduleVO = null;
	private TextView sunday;
	private TextView monday;
	private TextView tuesday;
	private TextView thursday;
	private TextView wednesday;
	private TextView friday;
	private TextView saturday;
	private ListView listView;
	private Button bt_add_schedule;
	private int step;
	private int selectId;
	private int selectItem;
	private int scheduleStatus=3; //0显示未开始 ，1显示正在进行 ，2显示已完成 ，3显示所有
	SharedPreferences preferences ;
	TextView bg_slider;
	int startLeft;
	ArrayList<String> scheduleDate;
	SimpleAdapter adapter;
	List<HashMap<String, String>> data;
	
	int week[]={
			R.id.sun,
			R.id.mon,
			R.id.tue,
			R.id.thu,
			R.id.wed,
			R.id.fri,
			R.id.sat,
	};

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub 注释
		selectDay(v,v.getId());
	}
	
    public void selectDay(View v,int id){
    	for (int i = 0; i < week.length; i++) {
			if(id==week[i]){
				//设置底部动画
				MoveBg.moveFrontBg(bg_slider, startLeft, v.getWidth()*i, 0, 0);
				startLeft = v.getWidth()*i;
				scheduleDate=updateScheduleDate(scheduleDate, i-step);
				step=i;
				updateSchdule();
				//刷新数据
			}
		}
    }
	
	
	/**
	 * 创建菜单
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

//		menu.add(0, menu.FIRST, menu.FIRST, "今天");
//		menu.add(0, menu.FIRST+1, menu.FIRST+1, "跳转");
//		menu.add(0, menu.FIRST+2, menu.FIRST+2, "日程");
//		menu.add(0, menu.FIRST+3, menu.FIRST+3, "日期转换");
		menu.add(0, menu.FIRST, menu.FIRST, "今天日程");
//		menu.add(0, menu.FIRST+1, menu.FIRST+1, "本周日程");
		menu.add(0, menu.FIRST+1, menu.FIRST+1, "本月日程");
		menu.add(0, menu.FIRST+2, menu.FIRST+2, "日程按状态显示");
//		menu.add(0, menu.FIRST+3, menu.FIRST+3, "日期转换");
		return super.onCreateOptionsMenu(menu);
	}
	
	private ArrayList<String> updateScheduleDate(ArrayList<String> oldScheduleDate,int steps){
		Calendar c=Calendar.getInstance();
		c.set(Integer.valueOf(oldScheduleDate.get(0)),Integer.valueOf( oldScheduleDate.get(1))-1, Integer.valueOf(Integer.valueOf(oldScheduleDate.get(2))+steps));
//		return makeScheduleDate(oldScheduleDate.get(0), oldScheduleDate.get(1), String.valueOf((Integer.valueOf(oldScheduleDate.get(2))+steps)), c.get(Calendar.DAY_OF_WEEK)-1);
		return makeScheduleDate(String.valueOf(c.get(Calendar.YEAR)),String.valueOf(c.get(Calendar.MONTH)+1), String.valueOf((String.valueOf(c.get(Calendar.DAY_OF_MONTH)))), c.get(Calendar.DAY_OF_WEEK)-1);
	}
	
	public ArrayList<String> makeScheduleDate(String scheduleYear,String scheduleMonth,String scheduleDay,int position){
		String week = "";
		//得到这一天是星期几
        switch(position%7){
        case 0:
      	  week = "星期日";
      	  break;
        case 1:
      	  week = "星期一";
      	  break;
        case 2:
      	  week = "星期二";
      	  break;
        case 3:
      	  week = "星期三";
      	  break;
        case 4:
      	  week = "星期四";
      	  break;
        case 5:
      	  week = "星期五";
      	  break;
        case 6:
      	  week = "星期六";
      	  break;
        }
		 
        ArrayList<String> scheduleDate = new ArrayList<String>();
        scheduleDate.add(scheduleYear);
        scheduleDate.add(scheduleMonth);
        scheduleDate.add(scheduleDay);
        scheduleDate.add(week);
        //scheduleDate.add(scheduleLunarDay);
        return scheduleDate;
	}

	
	/**
	 * 选择菜单
	 */
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		Intent intent = new Intent();
        switch (item.getItemId()){
        case Menu.FIRST:
        	//设置默认启动更改为 当天
	        Editor eDay=preferences.edit();
	        eDay.putString("CalendarDefaultLunchMode", "DayCalendar");
	        eDay.commit();
			updateSchdule();
        	Date date = new Date();
	    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
	    	String currentDate = sdf.format(date);  //当期日期
	    	String year_c = currentDate.split("-")[0];
	    	String month_c = currentDate.split("-")[1];
	    	String day_c = currentDate.split("-")[2];
	    	Calendar car=Calendar.getInstance();
	    	car.setTime(new Date());
	    	ArrayList<String> scheduleDate = makeScheduleDate(year_c, month_c, day_c,car.get(Calendar.DAY_OF_WEEK)-1);
            intent.putStringArrayListExtra("scheduleDate", scheduleDate);
			intent.setClass(CalendarWeekActivity.this, ScheduleInfoView.class);
			startActivity(intent);
			finish();
        	break;
        case Menu.FIRST+1:
        	//设置默认启动更改为 当天
	        Editor eMonth=preferences.edit();
	        eMonth.putString("CalendarDefaultLunchMode", "MonthCalendar");
	        eMonth.commit();
			intent.setClass(CalendarWeekActivity.this, CalendarActivity.class);
			startActivity(intent);
			finish();
        	break;
        case Menu.FIRST+2:
        	AlertDialog.Builder builder =new Builder(this);
            builder.setTitle("请选择切换的模式")
                   .setItems(new String[]{"显示未开始","显示正在进行","显示已完成","显示所有"}, new OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
							scheduleStatus = which;
							Editor e=preferences.edit();
							e.putInt("scheduleStatus", scheduleStatus);
							e.commit();
							updateSchdule();
					}
				}).show();
        	break;
        }
		return super.onMenuItemSelected(featureId, item);
	}

	@Override
	protected int initLayout() {
		// TODO Auto-generated method stub
		return R.layout.calendar_week;
	}

	@Override
	protected View initCustomLayout() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void initViewCmp() {
		// TODO Auto-generated method stub
		Button btn_Contact =(Button)findViewById(R.id.contact);
		Button btn_carlendar=(Button)findViewById(R.id.schedule_and_carlendar);
		btn_carlendar.setBackgroundResource(R.drawable.home_btn_bg_d);
		Button btn_search=(Button)findViewById(R.id.search_contact_schedule);
		Button note_book=(Button)findViewById(R.id.note_book);
		Button btn_attention = (Button)findViewById(R.id.attention_contact);
		Button title_bt_setting=(Button)findViewById(R.id.title_bt_setting);
		title_bt_setting.setVisibility(View.GONE);
		((TextView)findViewById(R.id.title_txt)).setText("日历与任务");
		btn_Contact.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent_main = new Intent();
				intent_main.setClass(CalendarWeekActivity.this, MainActivity.class);
	            startActivity(intent_main);
			}
		});
		btn_search.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent_search = new Intent();
	            intent_search.setClass(CalendarWeekActivity.this, SearchActivity.class);
	            startActivity(intent_search);
			}
		});
		note_book.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent noteIntent = new Intent();
	            noteIntent.setClass(CalendarWeekActivity.this, NoteBookActivity.class);
	            startActivity(noteIntent);
			}
		});
		btn_attention.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				 Intent aatentionIntent = new Intent();
		            aatentionIntent.setClass(CalendarWeekActivity.this, ContactAttentionActivity.class);
		            startActivity(aatentionIntent);
			}
		});

		sunday = (TextView) findViewById(R.id.sun);
		monday = (TextView) findViewById(R.id.mon);
		tuesday = (TextView) findViewById(R.id.tue);
		thursday = (TextView) findViewById(R.id.thu);
		wednesday = (TextView) findViewById(R.id.wed);
		friday = (TextView) findViewById(R.id.fri);
		saturday = (TextView) findViewById(R.id.sat);
		bg_slider = (TextView) findViewById(R.id.bg_slider);
		bt_add_schedule=(Button)findViewById(R.id.bt_add_contacts);
		bt_add_schedule.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intentAdd = new Intent();
				intentAdd.putExtra("operateType", "add");
		        intentAdd.putStringArrayListExtra("scheduleDate", scheduleDate);
		        intentAdd.putExtra("from", "CalendarWeek");
		        intentAdd.setClass(CalendarWeekActivity.this, ScheduleView.class);
		        startActivity(intentAdd);
			}
		});
		listView = (ListView) findViewById(R.id.week_schdule_list);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				LinearLayout itemDetail = (LinearLayout) arg1
						.findViewById(R.id.schdule_detail);
				if (itemDetail.getVisibility() == View.GONE) {
					itemDetail.setVisibility(View.VISIBLE);
				} else {
					itemDetail.setVisibility(View.GONE);
				}
			}
		});
		listView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				selectItem=arg2;
				selectId = Integer.valueOf(data.get(arg2).get("scheduleID"));
				// TODO Auto-generated method stub
				new AlertDialog.Builder(CalendarWeekActivity.this)
				               .setTitle("请选择操作")
				               .setItems(new String[]{"修改日程","删除日程"}, new OnClickListener() {
								
								@Override
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
									if(which==0){
//										new AlertDialog.Builder(CalendarWeekActivity.this)
//							               			   .setMessage("您选择了修改日程").show();
										Intent intentEdit = new Intent();
					                	ScheduleVO scheduleVO = dao.getScheduleByID(selectId);
					                	intentEdit.putExtra("operateType", "edit");
					                	intentEdit.putExtra("schedule", scheduleVO);
					                	intentEdit.putExtra("from", "CalendarWeek");
					        			intentEdit.setClass(CalendarWeekActivity.this, ScheduleView.class);
					    		        startActivity(intentEdit);
									}
									if(which==1){
//										new AlertDialog.Builder(CalendarWeekActivity.this)
//										               .setMessage("您选择了删除日程").show();
										Intent intent = new Intent(CalendarWeekActivity.this,
					        					RepeatingAlarm.class);
					            		PendingIntent sender = PendingIntent.getBroadcast(CalendarWeekActivity.this,
					            				selectId, intent, 0);
					        			// And cancel the alarm.
					        			AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
					        			am.cancel(sender);
					        			//删除任务
					                	dao.delete(selectId);
										data.remove(selectItem);
										adapter.notifyDataSetChanged();
									}
								}
							}).show();
				return false;
			}
		});
		Calendar car=Calendar.getInstance();
		Date date = new Date();
    	car.setTime(date);
		int weekFlag=car.get(Calendar.DAY_OF_WEEK)-1;
		((TextView) findViewById(week[weekFlag])).setTextColor(Color.RED);
		WindowManager wm=this.getWindowManager();
		int width=wm.getDefaultDisplay().getWidth()/7;
		MoveBg.moveFrontBg(bg_slider, startLeft,width*weekFlag, 0, 0);
		startLeft = width*weekFlag;
		preferences=getSharedPreferences("scheduleStatusMode", Context.MODE_PRIVATE);
		scheduleStatus = preferences.getInt("scheduleStatus", 3);
		dao = new ScheduleDAO(this);
		data=new ArrayList<HashMap<String,String>>();
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
    	String currentDate = sdf.format(date);  //当期日期
    	String year_c = currentDate.split("-")[0];
    	String month_c = currentDate.split("-")[1];
    	String day_c = currentDate.split("-")[2];
    	step=car.get(Calendar.DAY_OF_WEEK)-1;
    	scheduleDate = makeScheduleDate(year_c, month_c, day_c,car.get(Calendar.DAY_OF_WEEK)-1);
		String[] scheduleIDs = dao.getScheduleByTagDate(Integer.parseInt(scheduleDate.get(0)), Integer.parseInt(scheduleDate.get(1)), Integer.parseInt(scheduleDate.get(2)),scheduleStatus);
		ScheduleVO scheduleVO = new ScheduleVO();
		for (int i = 0; i < scheduleIDs.length; i++) {
			scheduleVO = dao.getScheduleByID(Integer.parseInt(scheduleIDs[i]));
			HashMap<String, String> map=new HashMap<String, String>();
			map.put("scheduleID",String.valueOf(scheduleVO.getScheduleID()));
			map.put("scheduleTitle",scheduleVO.getScheduleTitle()+"\t\t"+CalendarConstant.sch_type[scheduleVO.getScheduleTypeID()]);
			map.put("scheduleDate", scheduleVO.getScheduleDate());
			map.put("scheduleTypeID", CalendarConstant.sch_type[scheduleVO.getScheduleTypeID()]);
			map.put("scheduleContent",scheduleVO.getScheduleContent());
			map.put("scheduleStatus",convertStatusFlags(Integer.valueOf(scheduleVO.getScheduleStatus())));
			data.add(map);
		}
		adapter=new SimpleAdapter(this, data, R.layout.schdule_week_item, new String[]{"scheduleTitle","scheduleStatus","scheduleContent","scheduleDate"},new int[]{R.id.schedule_title,R.id.schedule_status,R.id.schedule_content,R.id.schedule_date});
        listView.setAdapter(adapter);
	}

	 public static int getWidth(View view)
	    {
	        int w = View.MeasureSpec.makeMeasureSpec(0,
	                View.MeasureSpec.UNSPECIFIED);
	        int h = View.MeasureSpec.makeMeasureSpec(0,
	                View.MeasureSpec.UNSPECIFIED);
	        view.measure(w, h);
	        return view.getMeasuredWidth();
	    }
	
	@Override
	protected void initListener() {
		// TODO Auto-generated method stub
		 sunday.setOnClickListener(this);
         monday.setOnClickListener(this);
         tuesday.setOnClickListener(this);
         thursday.setOnClickListener(this);
         wednesday.setOnClickListener(this);
         friday.setOnClickListener(this);
         saturday.setOnClickListener(this);
	}

	@Override
	protected void initData() {
		// TODO Auto-generated method stub
		updateSchdule();
	}
	
	private void updateSchdule(){
		String[] scheduleIDs = dao.getScheduleByTagDate(Integer.parseInt(scheduleDate.get(0)), Integer.parseInt(scheduleDate.get(1)), Integer.parseInt(scheduleDate.get(2)),scheduleStatus);
		data.clear();
		ScheduleVO scheduleVO = new ScheduleVO();
		for (int i = 0; i < scheduleIDs.length; i++) {
			scheduleVO = dao.getScheduleByID(Integer.parseInt(scheduleIDs[i]));
			HashMap<String, String> map=new HashMap<String, String>();
			map.put("scheduleID",String.valueOf(scheduleVO.getScheduleID()));
			map.put("scheduleTitle",scheduleVO.getScheduleTitle()+"\t\t"+CalendarConstant.sch_type[scheduleVO.getScheduleTypeID()]);
			map.put("scheduleDate", scheduleVO.getScheduleDate());
			map.put("scheduleTypeID", CalendarConstant.sch_type[scheduleVO.getScheduleTypeID()]);
			map.put("scheduleContent",scheduleVO.getScheduleContent());
			map.put("scheduleStatus",convertStatusFlags(Integer.valueOf(scheduleVO.getScheduleStatus())));
			data.add(map);
		}
		adapter.notifyDataSetChanged();
	}

	@Override
	protected void initAsycnData() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void changeDefaultSetting() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		dao.destoryDB();
		super.onDestroy();
	}
	
	private String convertStatusFlags(int flag){
		switch (flag) {
			case 0:
				return "未开始";
			case 1:
				return "进行中";
			case 2:
				return "已结束";
			default:
				return "";	
		}
	}
}
